//
//  LCTravelDetailViewController.m
//  lechuang
//
//  Created by Mr_hi on 2023/6/6.
//  Copyright © 2023 Mooyi. All rights reserved.
//

#import "LCTravelDetailViewController.h"
#import <WebKit/WebKit.h>

#import "LCTravelEnrollViewController.h"

@interface LCTravelDetailViewController ()<WKNavigationDelegate>

@property (weak, nonatomic) IBOutlet UIView *contentView;

/** 进度条 */
@property (nonatomic, strong) UIProgressView *myProgressView;
/** webView */
@property (nonatomic, strong) WKWebView *myWebView;

@property (weak, nonatomic) IBOutlet UIButton *enrollBtn;

@end

@implementation LCTravelDetailViewController

- (IBAction)backAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self loadData];
}

-(void)configUI {
    [self.contentView addSubview:self.myWebView];
    [self.contentView addSubview:self.myProgressView];
    
    [self.myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.equalTo(self.contentView);
    }];
    [self.myProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.contentView);
        make.height.offset(0.8*proW);
    }];
}

- (void)loadData {
    if (![self.travel.isentry isEqualToString:@"0"]) {
        [self.enrollBtn setTitle:@"已报名" forState:UIControlStateNormal];
        self.enrollBtn.backgroundColor = XWXPrimaryColor(@"#CCCCCC");
        self.enrollBtn.userInteractionEnabled = NO;
    } else {
        [self.enrollBtn setTitle:@"立即报名" forState:UIControlStateNormal];
        self.enrollBtn.backgroundColor = XWXPrimaryColor(@"#16A1E3");
        self.enrollBtn.userInteractionEnabled = YES;
    }
    // 进行中文转码
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:TravelDetailWeb(self.travel.tripid)]];
    [self.myWebView loadRequest:request];
}

#pragma mark - 进度条监听的代理回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.myWebView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.myProgressView.alpha = 1.0f;
        [UIView animateWithDuration:0.3 animations:^{
            [self.myProgressView setProgress:newprogress animated:YES];
        }];
        if (newprogress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.myProgressView.alpha = 0.0f;
            } completion:^(BOOL finished) {
                [self.myProgressView setProgress:0 animated:NO];
            }];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"开始加载网页");
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
}

//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败");
}

- (void)dealloc {
    [self.myWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}

#pragma mark - getter and setter
- (UIProgressView *)myProgressView {
    if (_myProgressView == nil) {
        _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0)];
        _myProgressView.tintColor = [UIColor whiteColor];
        _myProgressView.trackTintColor = [UIColor colorWithHexString:@"#F2F2F2"];
    }
    return _myProgressView;
}

- (WKWebView *)myWebView {
    if(_myWebView == nil) {
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        NSString * webWidth = @"";
        if (@available(iOS 11, *)) {
            webWidth = @"device-width";
        }else{
            webWidth = [NSString stringWithFormat:@"%f",[UIScreen mainScreen].scale * ScreenW];
        }
        NSString *jSString = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%@'); document.getElementsByTagName('head')[0].appendChild(meta);",webWidth];

        WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [userContentController addUserScript:wkUserScript];
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.userContentController = userContentController;
        _myWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
        _myWebView.navigationDelegate = self;
        _myWebView.opaque = NO;
        _myWebView.multipleTouchEnabled = YES;
        [_myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _myWebView;
}

- (IBAction)enrollBtnAction:(UIButton *)sender {
    if (![self.travel.isentry isEqualToString:@"0"]) {
        [self showErrorText:@"你已经报名了该项目"];
        return;
    }
    LCTravelEnrollViewController * enrollVC = [LCTravelEnrollViewController xx_instantiateFromStoryboardNamed:@"Global"];
    enrollVC.tripid = self.travel.tripid;
    [self.navigationController pushViewController:enrollVC animated:YES];
}

@end
